package com.meixiang.activity.homes.shopping;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.request.BaseRequest;
import com.meixiang.R;
import com.meixiang.adapter.shopping.SearchHistoryAdapter;
import com.meixiang.dialog.AlertDialogFragment;
import com.meixiang.entity.shopping.result.SearchLogResult;
import com.meixiang.global.Config;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseActivity;
import com.meixiang.tool.Tool;
import com.meixiang.view.ClearEditText;
import com.meixiang.view.FixedListView;
import com.meixiang.view.flowlayout.CustomFlowAdapter;
import com.meixiang.view.flowlayout.CustomFlowLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 商品搜索界面
 *
 * @author LZRUI
 */
public class SearchGoodsActivity extends BaseActivity implements TextWatcher, AdapterView.OnItemClickListener {

    private static final String TAG = "SearchGoodsActivity";

    @Bind(R.id.tv_option)
    TextView tvOption;
    @Bind(R.id.tv_search_hint)
    TextView tvSearchHint;
    @Bind(R.id.edt_search)
    ClearEditText edtSearch;
    @Bind(R.id.lv_search_history)
    FixedListView lvSearchHistory;
    @Bind(R.id.ll_clear_history)
    LinearLayout llClearHistory;
    @Bind(R.id.tag_flow)
    CustomFlowLayout tagFlow;
    @Bind(R.id.tv_search_history_hint)
    TextView tvSearchHistoryHint;
    @Bind(R.id.scroll_view)
    ScrollView scrollView;

    private boolean isSearch = false;
    private SearchHistoryAdapter adapter;
    private CustomFlowAdapter hotAdapter;
    private List<String> hotTagList = new ArrayList<>();
    private List<String> historyList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_search_goods);
        ButterKnife.bind(this);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        HttpUtils.tagCancelRequest(TAG);
    }

    @Override
    protected void initTitle() {

    }

    @SuppressWarnings("unchecked")
    @Override
    protected void initView() {
        edtSearch.addTextChangedListener(this);
        adapter = new SearchHistoryAdapter();
        lvSearchHistory.setAdapter(adapter);
        lvSearchHistory.setOnItemClickListener(this);

        tagFlow.setMargin(10, 0, 5, 15);
        // 必须在设置adapter之前设置监听
        tagFlow.setOnFlowItemClickListener(new CustomFlowLayout.OnFlowItemClickListener() {
            @Override
            public void onItemClick(int position, View view) {
                if (Tool.isFastDoubleClick()) return;
                isSearch = true;
                reBack(hotTagList.get(position));
            }
        });
        tagFlow.setAdapter(hotAdapter = new CustomFlowAdapter(hotTagList) {
            @Override
            public View getView(CustomFlowLayout parent, int position, Object o) {
                TextView tvTag = (TextView) LayoutInflater.from(SearchGoodsActivity.this).inflate(R.layout.view_hot_search_tag, parent, false);
                tvTag.setText((String) o);
                return tvTag;
            }
        });
    }

    @Override
    protected void setData() {
        HttpUtils.post(Config.SEARCH_LOG, TAG, null, new HttpCallBack(SearchGoodsActivity.this) {

            @Override
            public void onBefore(BaseRequest request) {
                if (!Tool.isNetworkAvailable(activity)) {
                    OkHttpUtils.getInstance().cancelTag(SearchGoodsActivity.this);
                    if (status == null || scrollView == null) return;
                    status.showNoNewWork(scrollView, null);
                } else {
                    if (status == null || scrollView == null) return;
                    status.showLoading(scrollView);
                }
            }

            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                SearchLogResult logResult = new Gson().fromJson(result.toString(), SearchLogResult.class);
                if (logResult != null) {
                    historyList = logResult.getHistoryList();
                    adapter.refreshList(historyList);
                    hotTagList.clear();
                    hotTagList.addAll(logResult.getHotList());
                    hotAdapter.notifyDataChanged();
                }
            }

            @Override
            public void onError(String code, String message) {

            }

            @Override
            public void onAfter(boolean isFromCache, JSONObject jsonObject, Call call, Response response, Exception e) {
                if (status == null || scrollView == null || adapter == null) return;
                if (hotAdapter.getCount() == 0 && adapter.getCount() == 0) {
                    status.showNoData(scrollView, "暂无热门标签");
                } else {
                    status.removeView();
                }
                historyIsEmpty(adapter.getCount() == 0);
            }
        });
    }

    private void historyIsEmpty(boolean isEmpty) {
        if (!isEmpty) {
            if (llClearHistory == null || tvSearchHistoryHint == null) return;
            llClearHistory.setVisibility(View.VISIBLE);
            tvSearchHistoryHint.setVisibility(View.VISIBLE);
        } else {
            if (llClearHistory == null || tvSearchHistoryHint == null) return;
            llClearHistory.setVisibility(View.GONE);
            tvSearchHistoryHint.setVisibility(View.GONE);
        }
    }

    @Override
    @OnClick({R.id.tv_option, R.id.fl_search, R.id.tv_clear_history})
    public void onClick(View view) {
        if (Tool.isFastDoubleClick()) return;
        switch (view.getId()) {
            // 取消（搜索）按钮
            case R.id.tv_option:
                reBack(edtSearch.getEditableText().toString().trim());
                break;
            // 点击显示EditText
            case R.id.fl_search:
                tvSearchHint.setVisibility(View.GONE);
                edtSearch.setVisibility(View.VISIBLE);
                edtSearch.requestFocus();
                break;
            // 清空搜索历史
            case R.id.tv_clear_history:
                new AlertDialogFragment.Builder()
                        .setContentText("确认要清空搜索历史？")
                        .setRightBtnText("取消")
                        .setLeftBtnText("确认")
                        .setLeftClickCallBack(new AlertDialogFragment.LeftClickCallBack() {
                            @Override
                            public void dialogLeftBtnClick() {
                                clearHistoryList();
                                adapter.clearList();
                                llClearHistory.setVisibility(View.GONE);
                                tvSearchHistoryHint.setVisibility(View.GONE);
                            }
                        })
                        .build()
                        .show(getSupportFragmentManager(), AlertDialogFragment.TAG);
                break;
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (s.length() > 0) {
            tvOption.setText("搜索");
            isSearch = true;
        } else {
            tvOption.setText("取消");
            isSearch = false;
        }
    }

    /**
     * 返回
     */
    private void reBack(String keyTag) {
        if (isSearch) {
            Intent intent = new Intent();
            intent.putExtra(ShoppingHomeActivity.SEARCH_KEY, keyTag);
            setResult(RESULT_OK, intent);
        }
        finish();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (historyList != null && !historyList.isEmpty()) {
            isSearch = true;
            reBack(historyList.get(position));
        }
    }

    /**
     * 清空搜索历史
     */
    private void clearHistoryList() {
        HttpUtils.post(Config.DELETE_HISTORY, TAG, null, new HttpCallBack(SearchGoodsActivity.this) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                try {
                    String msg = result.getString("message");
                    Toast.makeText(SearchGoodsActivity.this, msg, Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String code, String message) {
                Toast.makeText(SearchGoodsActivity.this, message, Toast.LENGTH_SHORT).show();
            }
        });
    }

}
